﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Ornithopter.FlashDiskHelper
{
    public class ByteConventer
    {
        private const long TeraByte = 1024 * GigaByte;
        private const long GigaByte = 1024 * MegaByte;
        private const long MegaByte = 1024 * KiloByte;
        private const long KiloByte = 1024;

        public static String Convert(object value, object parameter)
        {
            bool hideUnit;
            if (value == null)
            {
                return "--";
            }
            if (!bool.TryParse(parameter as string, out hideUnit))
                hideUnit = false;
            try
            {
                float bytes;
                if (!float.TryParse(value.ToString(), out bytes))
                {
                    return "--";
                }
                if (bytes == 0)
                {
                    return "--";
                }
                if (bytes > TeraByte)
                {
                    return ((float)bytes / (float)TeraByte).ToString("0.00") + GetUnitString(hideUnit, " TB");
                }
                else if (bytes > GigaByte)
                {
                    return ((float)bytes / (float)GigaByte).ToString("0.00") + GetUnitString(hideUnit, " GB");
                }
                else if (bytes > MegaByte)
                {
                    return (((float)bytes / (float)MegaByte)).ToString("0.00") + GetUnitString(hideUnit, " MB");
                }
                else if (bytes > KiloByte)
                {
                    return ((float)bytes / (float)KiloByte).ToString("0.00") + GetUnitString(hideUnit, " KB");
                }
                else return bytes + " Bytes";
            }
            catch
            {
                return value.ToString() + " Byte";
            }

        }

        private static string GetUnitString(bool hideUnit, string unit)
        {
            if (!hideUnit)
                return unit;
            else
                return null;
        }
    }
}
